package com.noble.meether.db.utils;

import android.os.Environment;

import com.noble.glamour.module.logic.application.App;
import com.noble.library.log.PLogger;
import com.noble.library.permission.PermissionUtil;
import com.noble.library.permission.callback.PermissionListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * 数据库文件工具类
 */
public class DBFileUtil {

    /**
     * 拷贝数据库到sd卡
     */
    public static void copyDataBaseToSD() {
        PermissionUtil.checkStoragePermission(App.getContext(), new PermissionListener() {
            @Override
            public void success() {
                if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                    return;
                }
                File dbFile = new File(App.context.getDatabasePath(String.valueOf(App.uid)) + ".db");
                File file = new File(Environment.getExternalStorageDirectory(), "seeker.db");
                FileChannel inChannel = null, outChannel = null;
                try {
                    PLogger.d("db file copy");
                    file.createNewFile();
                    inChannel = new FileInputStream(dbFile).getChannel();
                    outChannel = new FileOutputStream(file).getChannel();
                    inChannel.transferTo(0, inChannel.size(), outChannel);
                } catch (Exception e) {
                    PLogger.d("db file copy fail");
                    e.printStackTrace();
                } finally {
                    try {
                        if (inChannel != null) {
                            inChannel.close();
                        }
                        if (outChannel != null) {
                            outChannel.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void fail() {
            }
        });
    }
}
